<template>
  <div>
    <el-form :rules="rules" ref="addForm" :label-position="labelPosition" label-width="80px" :model="addArticeForm">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="addArticeForm.title" placeholder="请输入标签"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="categoryId">
        <el-select v-model="addArticeForm.categoryId" placeholder="请选择">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <v-rich-editor ref="editor" v-model="addArticeForm.content"></v-rich-editor>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" plain @click="handlerSubmitArtice('addForm')">提交</el-button>
        <el-button v-if="isUpdate" type="primary" plain @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import VRichEditor from '@/components/VRichEditor'
export default {
  components:{
    VRichEditor
  },
   data() {
    var validateContent = (rule, value, callback) => {
      if (value === '<p><br></p>') {
        return callback(new Error('内容不能为空'));
      }
      callback();
    }
    return {
      activeIdx: '0',
      labelPosition: 'top',
      articleId: 0, 
      addArticeForm:{
        categoryId: "",
        title:"",
        content:"",
      },
      categoryList: [],
      rules: {
        title: [
           { required: true, message: '请输入标题', trigger: 'blur' },
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' },
        ],
        content: [
          { required: true, validator: validateContent, trigger: 'blur' },
        ]
      },
    };
  },
  created() {
    if (this.isUpdate) {
      this.articleId = this.$route.query.id
      this.handlerGetOnlyArticle(this.articleId)
    }
    this.handlerGetCategory()
  },
  methods: {
    async handlerGetCategory() {
      await this.$store.dispatch("category/get_category_list")
      this.categoryList = this.$store.state.category.categoryList
    },
    handlerSubmitArtice(formName) {
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            if (this.isUpdate) {
              this.handlerUpdateArticle()
            } else {
              this.handlerAddArticle()
            }
          } else {
            this.$notify.error({
              title: '错误',
              message: "请填写完整内容",
            });
            return false;
          }
      })
    },
    async handlerGetOnlyArticle(id) {
      let {data} = await this.$req.get({
        url: '/detail',
        data: {id},
      })
      let data0 = data.data;
      this.addArticeForm.categoryId = data0.category_id;
      this.addArticeForm.content = data0.content;
      this.addArticeForm.title = data0.title;
    },
    async handlerAddArticle() {
      let {data} = await this.$req.post({
        url: "/blog",
        data: this.addArticeForm,
      })
      if (data.code === 200) {
        this.$notify({
          title: '成功',
          message: data.msg,
          type: 'success'
        })
        this.addArticeForm.title = '';
        this.addArticeForm.categoryId = '';
        this.addArticeForm.content = '';
        // 清除文本框内容
        this.$refs.editor.clearAll()
        this.$router.push('/dashboard/article/center')
      } else {
        this.$notify.error({
          title: '错误',
          message: data.msg,
        });
      }
    },
    async handlerUpdateArticle() {
      let dataParams = {
        id: this.articleId,
        ...this.addArticeForm
      }
      let {data} = await this.$axios({
        method: 'PUT',
        url: "/blog",
        data: dataParams,
      })
      if (data.code === 200) {
        this.$notify({
          title: '成功',
          message: data.msg,
          type: 'success'
        })
        this.$router.go(-1)
      } else {
        this.$notify.error({
          title: '错误',
          message: data.msg,
        });
      }
      
    }
  },
  computed: {
    isUpdate() {
      return this.$route.path.endsWith('/update')
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if(from.path.endsWith('/update')) {
        vm.addArticeForm.categoryId = '';
        vm.addArticeForm.title = '';
        vm.addArticeForm.content = '';
        vm.$refs.editor.clearAll()
      }
    })
  }
}
</script>

<style>

</style>